'use strict'

const Controller = require('egg').Controller

const fail = {
  code: 500,
  msg: '失败',
  data: null,
}
class HomeController extends Controller {
  async index() {
    const { ctx } = this
    await ctx.render('index.html', {
      title: '记账本',
    })
  }

  async user() {
    const { ctx } = this
    const result = await ctx.service.home.user()
    ctx.body = result
  }

  async create() {
    const { ctx } = this
    const { title } = ctx.request.body
    ctx.body = {
      title,
    }
  }

  async addUser() {
    const { ctx } = this
    const { name } = ctx.request.body

    try {
      const result = this.service.home.addUser(name)
      if (result) {
        ctx.body = {
          code: 200,
          msg: '添加成功',
          data: result,
        }
      } else {
        ctx.body = fail
      }
    } catch (error) {
      ctx.body = fail
    }
  }

  async editUser() {
    const { ctx } = this
    const { id, name } = ctx.request.body
    // console.log(name)
    try {
      const result = await ctx.service.home.editUser(id, name)
      if (result) {
        ctx.body = {
          code: 200,
          msg: '编辑成功',
          data: result,
        }
      } else {
        ctx.body = fail
      }
    } catch (error) {
      ctx.body = fail
    }
  }

  async deleteUser() {
    const { ctx } = this
    const { id } = ctx.params
    try {
      const result = await ctx.service.home.deleteUser(id)
      if (result) {
        ctx.body = {
          code: 200,
          msg: '删除成功',
          data: null,
        }
      } else {
        ctx.body = fail
      }
    } catch (error) {
      ctx.body = fail
    }
  }
}

module.exports = HomeController
